package com.alvin.springshiro.configuration;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.context.annotation.PropertySource;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.FutureTask;


@Slf4j
@ControllerAdvice
@PropertySource("kafka.properties")
public class CustomExceptionHandler {

    private boolean connectFailedFlag = false;

    private final KafkaTemplate kafkaTemplate;

    public CustomExceptionHandler(KafkaTemplate kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    @ExceptionHandler(Exception.class)        //用于注释异常处理类，value属性指定需要拦截的异常类型
    public Object errorHandler(Exception e, HttpServletRequest request, HttpServletResponse response) {        //捕获异常并获取异常处理对象

        Map<String, Object> result = new HashMap<>();

        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        result.put("exception", e);
        result.put("timestamp", sdf.format(d));
        result.put("message", e.getMessage());    //获取异常信息
        result.put("path",request.getRequestURI());
        result.put("status",response.getStatus());

//        if(!connectFailedFlag){
//            ListenableFuture future = kafkaTemplate.send(new ProducerRecord<>("exception-handler-topic", request.getRequestURI(), e.toString()));
//
//            future.addCallback((re)->{},(exception)->{
//
//                log.error("发送异常日志至kafka异常，日志记录在本项目下。异常信息：", exception);
//                log.error("本地日志：访问 "+request.getRequestURI() +" 发生异常: ", e);
//
//                connectFailedFlag = true;
//            });
//
//        }else{
            log.error("本地日志：访问 "+request.getRequestURI() +" 发生异常: ", e);
//        }

        return new ModelAndView("error/genericErrorPage", result);        //将异常信息响应给浏览器
    }

}
